<template>
	<div class="wrapper">

		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">商家列表</h1>
				</section>
			</div>
		</header>

		<!-- 商家列表部分 -->
		<div class="business-list-container">
			<div 
				v-for="item in businessArr" 
				:key="item.businessId" 
				class="business-card"
			>
				<div class="business-img-wrapper">
					<img :src="getImg(item.businessImg)" @error="handleImageError" class="business-img" @click="toBusinessInfo(item.businessId)">
					<div class="business-img-quantity" v-show="item.quantity>0">{{item.quantity}}</div>
				</div>
				<div class="business-info" @click="toBusinessInfo(item.businessId)">
					<h3 class="business-name">{{item.businessName}}</h3>
					<div class="business-meta">
						<span class="meta-item">¥{{item.starPrice}}起送</span>
						<span class="meta-divider">|</span>
						<span class="meta-item">¥{{item.deliveryPrice}}配送</span>
					</div>
					<p class="business-desc">{{item.businessExplain}}</p>
				</div>
				<button 
					class="favorite-btn" 
					:class="{ active: item.isFavorite }" 
					@click.stop="toggleFavorite(item)"
				>
					<i class="material-icons">{{ item.isFavorite ? 'favorite' : 'favorite_border' }}</i>
				</button>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>

	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default{
		name:'BusinessList',
		data(){
			return {
				orderTypeId: this.$route.query.orderTypeId,
				businessArr:[],
				user:{},
				loadingFavorites: false
			}
		},
		created() {
			this.user = this.$getSessionStorage('user');
			
			//根据orderTypeId查询商家信息
			this.$axios.post('BusinessController/listBusinessByOrderTypeId',this.$qs.stringify({
				orderTypeId:this.orderTypeId
			})).then(response=>{
				this.businessArr = (response.data || []).map(b => ({
					...b,
					isFavorite: false
				}));
				//判断是否登录
				if(this.user!=null){
					this.listCart();
					this.loadFavoritesStatus();
				}
			}).catch(error=>{
				console.error(error);
			});
		},
		components:{
			AppFooter,BackButton
		},
		methods:{
		getImg(path){
			if(!path) return this.getDefaultImage();
			// 如果是完整的HTTP URL，直接返回
			if(path.startsWith('http')) return path;
			// 如果是 base64 格式，直接返回
			if(path.startsWith('data:image')) return path;
			// 如果是相对路径（以/开头），拼接服务器地址
			if(path.startsWith('/')) {
				// 如果已经是 /img/ 开头，直接拼接
				if(path.startsWith('/img/')) {
					return 'http://localhost:8888' + path;
				}
				// 如果是其他路径（如 /2024-10-26/xxx.jpg），需要添加 /img 前缀
				return 'http://localhost:8888/img' + path;
			}
			// 其他情况，添加服务器前缀和路径分隔符
			return 'http://localhost:8888/img/' + path;
		},
		getDefaultImage(){
			// 返回一个包含食物emoji的SVG图片
			const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="#f5f5f5" rx="10"/><text x="100" y="100" font-size="80" text-anchor="middle" dominant-baseline="central">🍕</text></svg>';
			return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
		},
		handleImageError(event){
			event.target.src = this.getDefaultImage();
		},
			listCart(){
				this.$axios.post('CartController/listCart',this.$qs.stringify({
					userId:this.user.userId
				})).then(response=>{
					let cartArr = response.data;
					//遍历所有食品列表
					for(let businessItem of this.businessArr){
						businessItem.quantity = 0;
						for(let cartItem of cartArr){
							if(cartItem.businessId==businessItem.businessId){
								businessItem.quantity += cartItem.quantity;
							}
						}
					}
					this.businessArr.sort();
				}).catch(error=>{
					console.error(error);
				});
			},
			toBusinessInfo(businessId){
				this.$router.push({path:'/businessInfo',query:{businessId:businessId}});
			},
			loadFavoritesStatus(){
				if(!this.user || !this.user.userId || this.businessArr.length === 0) return;
				this.loadingFavorites = true;
				this.$axios.get('favorites/list',{
					params:{ userId:this.user.userId }
				}).then(resp=>{
					if(resp.data && (resp.data.code===200 || resp.data.code==='200')){
						const favs = resp.data.result || [];
						const favIds = favs.map(f=>f.businessId);
						this.businessArr.forEach(b=>{
							b.isFavorite = favIds.includes(b.businessId);
						});
					}
				}).catch(err=>{
					console.error('加载收藏状态失败:',err);
				}).finally(()=>{
					this.loadingFavorites = false;
				});
			},
			toggleFavorite(item){
				if(!this.user || !this.user.userId){
					this.$toast?.info('请先登录');
					this.$router.push('/login');
					return;
				}
				const isFav = item.isFavorite;
				const url = isFav ? 'favorites/remove' : 'favorites/add';
				this.$axios.post(url,null,{
					params:{
						userId:this.user.userId,
						businessId:item.businessId
					}
				}).then(resp=>{
					if(resp.data && (resp.data.code===200 || resp.data.code==='200')){
						item.isFavorite = !isFav;
						this.$toast?.success(isFav ? '已取消收藏' : '收藏成功');
					}else{
						this.$toast?.error(resp.data.message || '操作失败');
					}
				}).catch(err=>{
					console.error('切换收藏失败:',err);
					this.$toast?.error('操作失败');
				});
			}
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 14vw;
	}

	/****************** header部分 ******************/
	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 商家列表部分 ******************/
	.business-list-container {
		width: 100%;
		padding: 0 3vw;
	}

	.business-card {
		width: 100%;
		background-color: #fff;
		border-radius: 16px;
		box-shadow: 0 2px 12px rgba(0,0,0,0.08);
		margin-bottom: 3vw;
		padding: 4vw;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		cursor: pointer;
		transition: all 0.3s ease;
		user-select: none;
	}

	.business-card:active {
		transform: scale(0.98);
		box-shadow: 0 1px 6px rgba(0,0,0,0.12);
	}

	.business-img-wrapper {
		position: relative;
		flex-shrink: 0;
	}

	.business-img {
		width: 22vw;
		height: 22vw;
		border-radius: 12px;
		object-fit: cover;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.business-img-quantity {
		position: absolute;
		top: -2vw;
		right: -2vw;
		width: 6vw;
		height: 6vw;
		background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
		color: #fff;
		font-size: 3.2vw;
		font-weight: 600;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		box-shadow: 0 2px 6px rgba(255,107,107,0.4);
		border: 2px solid #fff;
	}

	.business-info {
		flex: 1;
		margin-left: 4vw;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.business-name {
		font-size: 4.2vw;
		font-weight: 600;
		color: #333;
		margin: 0 0 2vw 0;
	}

	.business-meta {
		display: flex;
		align-items: center;
		margin-bottom: 2vw;
		gap: 2vw;
	}

	.meta-item {
		font-size: 3.2vw;
		color: #666;
	}

	.meta-divider {
		color: #ddd;
		font-size: 3vw;
	}

	.business-desc {
		font-size: 3.2vw;
		color: #999;
		margin: 0;
		line-height: 1.4;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.arrow-icon {
		font-size: 6vw;
		color: #ccc;
		flex-shrink: 0;
		margin-left: 2vw;
	}

	.favorite-btn {
		background: none;
		border: none;
		cursor: pointer;
		margin-left: 2vw;
		color: #ccc;
		flex-shrink: 0;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.favorite-btn .material-icons {
		font-size: 6vw;
	}

	.favorite-btn.active {
		color: #ff4d4f;
	}
</style>
